package com.ybkj.daijia.api.member.v3;

import com.ybkj.daijia.api.member.Error;
import com.ybkj.daijia.api.member.ErrorConstant;
import com.ybkj.daijia.api.member.SecurityUtils;
import com.ybkj.daijia.api.member.transport.ResultTransport;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Rate;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.RateService;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 客户评级
 */
@Controller("RateV3Controller")
@RequestMapping(value = "member/api/rest/v3")
public class RateController {

    private static final Logger logger = LoggerFactory.getLogger(RateController.class);

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private RateService rateService;
    @Autowired
    private OrderService orderService;

    /**
     * 用户评价
     *
     * @param phone     手机号
     * @param appKey
     * @param token     token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "rate", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport rate(
        String phone, Long driverId, String content, Float starLevel,
        Long orderId,
        String appKey, String token, String timestamp) {

        logger.debug(
            "recv phone:{},driverId:{},content{},starLevel:{},orderId:{},appKey:{},token:{},timestamp:{}",
            phone, driverId, content, starLevel, orderId, appKey, token, timestamp);

        if (StringUtils.isBlank(phone) || null == driverId || StringUtils.isBlank(content)
            || null == starLevel
            || null == orderId || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

//		if(!StringUtils.isNumeric(timestamp) || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
//			return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
//		}

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(phone));
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(content));
        params.add(String.valueOf(starLevel));
        params.add(String.valueOf(orderId));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        if (content.length() > 50) {
            return ResultTransport.getErrorBy(ErrorConstant.STRING_TOO_LONG);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        Driver driver = driverService.findOne(driverId);
//		if(null==driver){
//			return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS_ERROR);
//		}

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
        }
        if (!order.getStatus().equals(Order.ORDER_STATUS_FINISHED) && !order.getStatus()
            .equals(Order.ORDER_STATUS_BAODAN)) {
            return ResultTransport.getErrorBy(new Error(-14, "订单未完成，无法评价"));
        }

        Rate oldRate = rateService.findByMemberAndOrder(passenger.getId(), order.getId());
        if (null != oldRate) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_HASBEEN_RATE);
        }

        try {

            Rate rate = new Rate();

            rate.setTitle("无");
            rate.setContent(content);
            rate.setDriverId(order.getDriverId());
            rate.setDriverName(order.getDriverName());
            rate.setMemberPhone(phone);
            rate.setMemberId(passenger.getId());
            rate.setOrderId(order.getId());
            rate.setOrderNumber(order.getOrderNumber());

            if (StringUtils.isNotBlank(passenger.getName())) {
                rate.setMemberName(passenger.getName());
            } else {
                rate.setMemberName("先生/女士");
            }
            rate.setStarLevel(starLevel);

            rateService.rate(rate, driver, order);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 rate rate error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 用户查询评价
     *
     * @param phone     手机号
     * @param appKey
     * @param token     token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "pageRateByDriver", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport pageRateByDriver(
        Long driverId, Integer page, Integer limit,
        String appKey, String token, String timestamp) {

        logger.debug("recv driverId:{},page:{},limit:{}, appKey:{},token:{},timestamp:{}", driverId,
            page, limit, appKey, token, timestamp);

        if (null == driverId || null == page || null == limit || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

//		if(!StringUtils.isNumeric(timestamp) || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
//			return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
//		}

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Driver driver = driverService.findOne(driverId);
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS_ERROR);
        }

        try {

            Page<Rate> rates = rateService.pageRateByDriver(driver.getId(), page, limit);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(rates);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 rate pageRateByDriver error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


}
